<style>
  /* CSS */
  apple-pay-button {
    --apple-pay-button-width: 100%;
    --apple-pay-button-height: 30px;
    --apple-pay-button-border-radius: 5px;
    --apple-pay-button-padding: 9px 0px;
  }

  apple-pay-button:hover {
    opacity: 0.8;
  }
</style>
<div id="paypal-applepay-container-{{pay_id}}" style="width: 100%;"></div>

<script src="https://applepay.cdn-apple.com/jsapi/v1/apple-pay-sdk.js"></script>
<script>
  $(function () {

    function getProductCartParam() {
      var product_cart_param = "";
      var paypalecRet = moi.onEvent("paypalec_multiple_callback",{ payId: "{{pay_id | default :'0'}}", code: 0});
      var params = moi.getPageStorage('product_params' +{{pay_id}});
      if(!paypalecRet.params.code){
        moi.onEvent("paypalec_callback",{ payId: "{{pay_id | default :'0'}}"})
        var ret = moi.onEvent("payVerified", { property: [],product: params, code: 200 });
        if (ret.params.code !== 200) {
          return false
        }
        var product_selected = {
              product_id: params.product_id,
              sku_code: params.sku_code,
              quantity: params.quantity,
              data_from: moi.getUrlParam("data_from") || "{{data_from}}",
              property: ret.params.property

          }
        product_cart_param = encodeURIComponent(JSON.stringify(product_selected));
      }else{
        if(paypalecRet.params.code !== 200){
          return false
        }
        const cart_param = paypalecRet.params.data.map(el=>{
          return {
            product_id: params.product_id,
            sku_code: el.sku_code,
            quantity: el.add_quantity,
            data_from: moi.getUrlParam("data_from") || "{{data_from}}",
            property: []
          }
        })
        product_cart_param = encodeURIComponent(JSON.stringify(cart_param));
      }

      return product_cart_param;
    }

    async function setupApplepay() {
      if(!window['paypal']){
        return;
      }
      const applepay = paypal.Applepay();
      const {
        isEligible,
        countryCode,
        currencyCode,
        merchantCapabilities,
        supportedNetworks,
      } = await applepay.config();

      if (!isEligible) {
        throw new Error("applepay is not eligible");
      }

      document.getElementById("paypal-applepay-container-{{pay_id}}").innerHTML =
        '<apple-pay-button id="btn-appl-{{pay_id}}" buttonstyle="black" type="buy" locale="en">';

      document.getElementById("btn-appl-{{pay_id}}").addEventListener("click", onClick);

      async function onClick() {
        var amount = 0;
        var paypalecRet = moi.onEvent("paypalec_multiple_callback",{ payId: "{{pay_id | default :'0'}}", code: 0});
        var params = moi.getPageStorage('product_params' +{{pay_id}});
        if(!paypalecRet.params.code){
          moi.onEvent("paypalec_callback",{ payId: "{{pay_id | default :'0'}}"})
          var ret = moi.onEvent("payVerified", { property: [],product: params, code: 200 });
          if (ret.params.code !== 200) {
            return false
          }
          amount = formatMoney(Number(params.price).times(params.quantity),_GET_C_SETTING_("currency"),'',false,false).toString()
       
        }else{
          if(paypalecRet.params.code !== 200){
            return false
          }
          var price = paypalecRet.params.data
            .filter((item) => item.add_quantity)
            .map((item) => parseFloat(item.price).times(item.add_quantity))
            .reduce((a, b) => parseFloat(a) + parseFloat(b), 0);
          amount =  formatMoney(price, _GET_C_SETTING_("currency"),'',false,false)
        }
        
        const paymentRequest = {
          countryCode,
          currencyCode: _GET_C_SETTING_("currency").standard_code,
          merchantCapabilities,
          supportedNetworks,
          requiredBillingContactFields: [
            "name",
            "phone",
            "email",
            "postalAddress",
          ],
          requiredShippingContactFields: [
            "name",
            "phone",
            "email",
            "postalAddress",
          ],
          total: {
            label: "Total",
            amount: amount,
            type: "final",
          },
        };

        // eslint-disable-next-line no-undef
        let session = new ApplePaySession(4, paymentRequest);

        session.onvalidatemerchant = (event) => {
          applepay
            .validateMerchant({
              validationUrl: event.validationURL,
            })
            .then((payload) => {
              session.completeMerchantValidation(payload.merchantSession);
            })
            .catch((err) => {
              console.error(err);
              session.abort();
            });
        };

        session.onpaymentmethodselected = () => {
          session.completePaymentMethodSelection({
            newTotal: paymentRequest.total,
          });
        };

        session.onpaymentauthorized = async (event) => {
          try {
            /* Create Order on the Server Side */
            const { data } = await fetch('/checkouts/ecpayment/{{payment.interface_type}}/ECPay?is_ajax=1&payment_methods=apple&payment_id={{ payment.id }}&cart_param=' + getProductCartParam() + '&_ref=' + window.location.href, {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              }
            }).then((res) => res.json());
            /**
             * Confirm Payment 
             */
            await applepay.confirmOrder({ orderId: data.id, token: event.payment.token, billingContact: event.payment.billingContact, shippingContact: event.payment.shippingContact,email: event.payment.email });
            location.href = data.return_url;
            session.completePayment({
              status: window.ApplePaySession.STATUS_SUCCESS,
            });
          } catch (err) {
            console.error(err);
            session.completePayment({
              status: window.ApplePaySession.STATUS_FAILURE,
            });
          }
        };

        session.oncancel = () => {
          console.log("Apple Pay Cancelled !!")
        }

        session.begin();
      }
    }

    if (window['ApplePaySession'] && ApplePaySession?.supportsVersion(4) && ApplePaySession?.canMakePayments()) {
      setupApplepay().catch(console.error);
    }else{
      $("#paypal-applepay-container-{{pay_id}}").remove();
    }
  })


</script>